<?php
/**
 * Created by PhpStorm.
 * User: qingmu-523
 * Date: 2018/10/22
 * Time: 11:45
 */

namespace App\Command;

use Carbon\Carbon;
use PDO;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\OutputInterface;

class CreateI216XmlSendOut extends BaseCommand
{
    protected function configure()
    {
        $endTime = Carbon::now("Asia/Shanghai");
        $startTime = Carbon::now("Asia/Shanghai")->subMinute(10);
        $this
            ->setName('app:create-i216-sendout')
            ->setDescription('创建i216订单的发货xml，需要订单已经生成发货单')
            ->setHelp("创建i216订单的发货xml，需要订单已经生成发货单")// configure an argument / 配置一个参数
            ->addOption("tid", '', InputOption::VALUE_OPTIONAL, "为该tid的订单创建i216订单的发货xml，需要订单已经生成发货单", 0)
            ->addOption("orderSn", '', InputOption::VALUE_OPTIONAL, "为该订单号创建i216订单的发货xml，需要订单已经生成发货单", 0)
            ->addOption("startTime", "", InputOption::VALUE_REQUIRED, "截取订单开始时间，默认查找前十分钟", $startTime)
            ->addOption("status", "", InputOption::VALUE_REQUIRED, "业务状态码，S、F、C、P、D", "S")
            ->addOption("endTime", "", InputOption::VALUE_REQUIRED, "截取订单结束时间，默认查找前十分钟", $endTime);
    }

    protected function execute(InputInterface $input, OutputInterface $output)
    {
        $tid = $input->getOption('tid');
        $orderSn = $input->getOption('orderSn');
        $startTime = $input->getOption('startTime');
        $endTime = $input->getOption('endTime');
        $messageDateTime = date('Ymd') . "T" . date("Hi") . "+0800";
        $this->redis->setnx("unqiue:i216", 10000);
        $status = $input->getOption("status");
        if ($tid != 0) {
            $unqiue = $this->redis->incr("unqiue:i216");
            $infos = $this->omsdb->query("SELECT wms.sn,o.order_sn,o.channel_order_id,o.shipping_id,o.invoice_no,wms.id as ticket_id
            FROM `wms_tickets` as `wms`
            left join `order_info` as `o`
            on `wms`.`original_sn` = `o`.`order_sn`
            WHERE  wms.status_notify=:status_notify and wms.type_code = :type_code and o.channel_order_id = :channel_order_id limit 0,1", [ //wms.time_create >= :time_create and
                    ":status_notify" => -3,
                    ":type_code" => "XS",
                    ":channel_order_id" => "$tid",
                ]
            )->fetchAll(PDO::FETCH_ASSOC);
            $this->create_file($infos, $messageDateTime, $unqiue,$status);
            exit;

        } elseif ($orderSn != 0) {
            $unqiue = $this->redis->incr("unqiue:i216");
            $infos = $this->omsdb->query("SELECT wms.sn,o.order_sn,o.channel_order_id,o.shipping_id,o.invoice_no,wms.id as ticket_id
            FROM `wms_tickets` as `wms`
            left join `order_info` as `o`
            on `wms`.`original_sn` = `o`.`order_sn`
            WHERE  wms.status_notify=:status_notify and wms.type_code = :type_code and o.order_sn = :order_sn limit 0,1", [ //wms.time_create >= :time_create and
                    ":status_notify" => -3,
                    ":type_code" => "XS",
                    ":order_sn" => $orderSn,
                ]
            )->fetchAll(PDO::FETCH_ASSOC);
            $this->create_file($infos, $messageDateTime, $unqiue,$status);
            exit;
        } else {
            for ($page = 1; ; $page++) {
                echo memory_get_usage() . "    使用内存\n";
                $unqiue = $this->redis->incr("unqiue:i216");
                $messageDateTime = date('Ymd') . "T" . date("Hi") . "+0800";
                $pageSize = 1000;
                $limit = " limit " . ($page - 1) * $pageSize . "," . $pageSize;

                $infos = $this->omsdb->query("SELECT wms.sn,o.order_sn,o.channel_order_id,o.shipping_id,o.invoice_no,wms.id as ticket_id
                FROM `wms_tickets` as `wms`
                left join `order_info` as `o`
                on `wms`.`original_sn` = `o`.`order_sn`
                WHERE  wms.status_notify=:status_notify and wms.type_code = :type_code and wms.time_create >= :startTime and wms.time_create <= :endTime  $limit", [ //wms.time_create >= :time_create and
                        // ":time_create" => '2018-09-28 09:00:26',
                        ":status_notify" => -3,
                        ":type_code" => "XS",
                        ":startTime" => $startTime,
                        ":endTime" => $endTime,
                    ]
                )->fetchAll(PDO::FETCH_ASSOC);
                if (!$infos) {
                    echo('没有查询到数据');
                    exit;
                }
                $orderStatusXml = '';
                foreach ($infos as $info) {
                    //获取订单商品数据
                    $goods_infos = $this->omsdb->query("SELECT * from wms_tickets_goods where ticket_id = :ticket_id", [
                        ":ticket_id" => $info['ticket_id']])->fetchAll(PDO::FETCH_ASSOC);
                    // var_dump($goods_infos);
                    foreach ($goods_infos as $goods) { ////'.$goods['number_expected'].'
                        $order_line = $this->omsdb->query("SELECT order_line_id from hm_order_sn_line where order_sn = :order_sn and sku_sn = :sku_sn", [
                            ":order_sn" => $info['order_sn'],
                            ":sku_sn" => $goods['goods_sku_sn'],
                        ])->fetchAll(PDO::FETCH_ASSOC);
                        // var_dump($order_line);
                        $orderStatusXml .= $this->create_order($messageDateTime, $info['sn'],$info['channel_order_id'],$order_line[0]['order_line_id'],$goods['goods_sku_sn'],$info['order_sn'],$status);
                        /**                        $orderStatusXml .= '
                        <orderStatus>
                        <siteId>W148</siteId>
                        <countryCode>CN</countryCode>
                        <statusdateTime>' . $messageDateTime . '</statusdateTime>
                        <consignmentNumber>' . $info['sn'] . '</consignmentNumber>
                        <consignmentLineItemNumber>6</consignmentLineItemNumber>
                        <salesOrderNumber>' . $info['channel_order_id'] . '</salesOrderNumber>
                        <salesOrderLineItemNumber>' . $order_line[0]['order_line_id'] . '</salesOrderLineItemNumber>
                        <status>' . $status ? "S" : "F" . '</status>
                        <sku>' . $goods['goods_sku_sn'] . '</sku>
                        <shippedStatus>
                        <orderVersion>T</orderVersion>
                        <wmsInternalParcelNumber/>
                        <quantity>1</quantity>
                        <season>201808</season>
                        <countryOfOrigin>BD</countryOfOrigin>
                        <hmOrder>141540</hmOrder>
                        <shipmentNumber>1234567890</shipmentNumber>
                        <carrierName>SF</carrierName>
                        <carrierTrackingNumber>1234567890</carrierTrackingNumber>
                        <trackingHyperlink>http://www.sf-express.com/</trackingHyperlink>
                        <referenceField1>' . $info['order_sn'] . '</referenceField1>
                        <referenceField2/>
                        </shippedStatus>
                        </orderStatus>
                        ';
                         * */
                    }
                }

// $date = microtime_format('YmdHisx',microtime_float());
                $date = date("YmdHis");
// $doc->save("./xml/I216_LF01_QM_00067353_000_$date.xml");
                $file = "I216_LF01_QM_000{$unqiue}_000_$date";
                $xml =
                    '<?xml version="1.0" encoding="UTF-8" standalone="yes" ?>
                <order_status:businessTransaction xmlns:order_status=\'urn:hm:wms:orderStatus:xsd:1.3\' xmlns:shared_common=\'urn:hm:shared:shared_common:xsd:1\' xmlns:xsi=\'http://www.w3.org/2001/XMLSchema-instance\' version="1.3" >
                <messageMetadata>
                    <messageDateTime>' . $messageDateTime . '</messageDateTime>
                    <sourceSystem>LF01 WMS</sourceSystem>
                    <receivingSystem>HM GOEP</receivingSystem>
                    <messageType>Order Status Update</messageType>
                    <messageId/>
                    <originalFileName>WMSSHP_' . $file . '.txt</originalFileName>
                </messageMetadata>
                <orderStatuses>
                ' . $orderStatusXml . '
                </orderStatuses>
                </order_status:businessTransaction>
                ';
                $content = str_replace("\n", "", $xml);

                file_put_contents("./xml/{$file}.xml", $content, FILE_USE_INCLUDE_PATH);
                unset($infos);
                var_dump("./xml/{$file}.xml");
            }
        }

    }

    function create_file($infos, $messageDateTime, $unqiue,$status)
    {
        if (!$infos) {
            echo('没有查询到数据');
            exit;
        }
// var_dump($oms_db->last());
        // echo '数据';
        // var_dump($infos);
        $orderStatusXml = '';
        foreach ($infos as $info) {
            //获取订单商品数据
            $goods_infos = $this->omsdb->query("SELECT * from wms_tickets_goods where ticket_id = :ticket_id", [
                ":ticket_id" => $info['ticket_id']])->fetchAll(PDO::FETCH_ASSOC);
            // var_dump($goods_infos);
            foreach ($goods_infos as $goods) { ////'.$goods['number_expected'].'
                $order_line = $this->omsdb->query("SELECT order_line_id from hm_order_sn_line where order_sn = :order_sn and sku_sn = :sku_sn", [
                    ":order_sn" => $info['order_sn'],
                    ":sku_sn" => $goods['goods_sku_sn'],
                ])->fetchAll(PDO::FETCH_ASSOC);
                foreach ($order_line as $order_line_item){
                    $orderStatusXml .= $this->create_order($messageDateTime,$info['sn'],$info['channel_order_id'],$order_line_item['order_line_id'],$goods['goods_sku_sn'],$info['order_sn'],$status);
                }
                // var_dump($order_line);
//                $orderStatusXml .= $this->create_order($messageDateTime,$info['sn'],$info['channel_order_id'],$order_line[0]['order_line_id'],$goods['goods_sku_sn'],$info['order_sn'],$status);
                /**     $orderStatusXml .= '
                <orderStatus>
                <siteId>W148</siteId>
                <countryCode>CN</countryCode>
                <statusdateTime>' . $messageDateTime . '</statusdateTime>
                <consignmentNumber>' . $info['sn'] . '</consignmentNumber>
                <consignmentLineItemNumber>6</consignmentLineItemNumber>
                <salesOrderNumber>' . $info['channel_order_id'] . '</salesOrderNumber>
                <salesOrderLineItemNumber>' . $order_line[0]['order_line_id'] . '</salesOrderLineItemNumber>
                <status>S</status>
                <sku>' . $goods['goods_sku_sn'] . '</sku>
                <shippedStatus>
                <orderVersion>T</orderVersion>
                <wmsInternalParcelNumber/>
                <quantity>1</quantity>
                <season>201808</season>
                <countryOfOrigin>BD</countryOfOrigin>
                <hmOrder>141540</hmOrder>
                <shipmentNumber>1234567890</shipmentNumber>
                <carrierName>SF</carrierName>
                <carrierTrackingNumber>1234567890</carrierTrackingNumber>
                <trackingHyperlink>http://www.sf-express.com/</trackingHyperlink>
                <referenceField1>' . $info['order_sn'] . '</referenceField1>
                <referenceField2/>
                </shippedStatus>
                </orderStatus>
                ';
                 * */
            }
        }

// $date = microtime_format('YmdHisx',microtime_float());
        $date = date("YmdHis");
// $doc->save("./xml/I216_LF01_QM_00067353_000_$date.xml");
        $file = "I216_LF01_QM_000{$unqiue}_000_$date";
        $xml =
            '<?xml version="1.0" encoding="UTF-8" standalone="yes" ?>
            <order_status:businessTransaction xmlns:order_status=\'urn:hm:wms:orderStatus:xsd:1.3\' xmlns:shared_common=\'urn:hm:shared:shared_common:xsd:1\' xmlns:xsi=\'http://www.w3.org/2001/XMLSchema-instance\' version="1.3" >
            <messageMetadata>
                <messageDateTime>' . $messageDateTime . '</messageDateTime>
                <sourceSystem>LF01 WMS</sourceSystem>
                <receivingSystem>HM GOEP</receivingSystem>
                <messageType>Order Status Update</messageType>
                <messageId/>
                <originalFileName>WMSSHP_' . $file . '.txt</originalFileName>
            </messageMetadata>
            <orderStatuses>
            ' . $orderStatusXml . '
            </orderStatuses>
            </order_status:businessTransaction>
            ';
        $content = str_replace("\n", "", $xml);

        file_put_contents("./xml/{$file}.xml", $content, FILE_USE_INCLUDE_PATH);
        unset($infos);
        var_dump("./xml/{$file}.xml");
    }

    public function create_order($messageDateTime, $sn, $channel_order_id, $order_line_id, $goods_sku_sn, $order_sn,$status)
    {
        if ($status == 'S'){
            return '
           <orderStatus>
                        <siteId>W148</siteId>
                        <countryCode>CN</countryCode>
                        <statusdateTime>' . $messageDateTime . '</statusdateTime>
                        <consignmentNumber>' . $sn . '</consignmentNumber>
                        <consignmentLineItemNumber>6</consignmentLineItemNumber>
                        <salesOrderNumber>' . $channel_order_id . '</salesOrderNumber>
                        <salesOrderLineItemNumber>' . $order_line_id . '</salesOrderLineItemNumber>
                        <status>S</status>
                        <sku>' . $goods_sku_sn . '</sku>
                        <shippedStatus>
                            <orderVersion>T</orderVersion>
                            <wmsInternalParcelNumber/>
                            <quantity>1</quantity>
                            <season>201808</season>
                            <countryOfOrigin>BD</countryOfOrigin>
                            <hmOrder>141540</hmOrder>
                            <shipmentNumber>1234567890</shipmentNumber>
                            <carrierName>SF</carrierName>
                            <carrierTrackingNumber>1234567890</carrierTrackingNumber>
                            <trackingHyperlink>http://www.sf-express.com/</trackingHyperlink>
                            <referenceField1>' . $order_sn . '</referenceField1>
                            <referenceField2/>
                        </shippedStatus>
                    </orderStatus> 
        ';
        }elseif ($status == 'F'){
            return '
            <orderStatus>
                  <siteId>W148</siteId>
                  <countryCode>CN</countryCode>
                  <statusdateTime>' . $messageDateTime . '</statusdateTime>
                  <consignmentNumber>' . $sn . '</consignmentNumber>
                  <consignmentLineItemNumber>6</consignmentLineItemNumber>
                  <salesOrderNumber>' . $channel_order_id . '</salesOrderNumber>
                  <salesOrderLineItemNumber>' . $order_line_id . '</salesOrderLineItemNumber>
                  <status>F</status>
                  <sku>' . $goods_sku_sn . '</sku>
                  <failedDeliveryStatus>
                    <orderVersion>T</orderVersion>
                    <wmsInternalParcelNumber/>
                    <quantity>1</quantity>
                    <season>201808</season>
                    <countryOfOrigin>CN</countryOfOrigin>
                    <hmOrder>111313</hmOrder>
                    <shipmentNumber/>
                    <carrierName>SF</carrierName>
                    <carrierTrackingNumber>767609217849</carrierTrackingNumber>
                    <trackingHyperlink>http://www.sf-express.com/</trackingHyperlink>
                    <referenceField1>' . $order_sn . '</referenceField1>
                    <referenceField2/>
                  </failedDeliveryStatus>
            </orderStatus>
        ';
        }elseif ($status == 'C'){
            return '
            <orderStatus>
                  <siteId>W148</siteId>
                  <countryCode>CN</countryCode>
                  <statusdateTime>' . $messageDateTime . '</statusdateTime>
                  <consignmentNumber>' . $sn . '</consignmentNumber>
                  <consignmentLineItemNumber>6</consignmentLineItemNumber>
                  <salesOrderNumber>' . $channel_order_id . '</salesOrderNumber>
                  <salesOrderLineItemNumber>' . $order_line_id . '</salesOrderLineItemNumber>
                  <status>C</status>
                  <sku>' . $goods_sku_sn . '</sku>
                  <createStatus>
                        <orderVersion>T</orderVersion>
                        <quantity>1</quantity>
                        <carrierName>SF</carrierName>
                        <referenceField1>' . $order_sn . '</referenceField1>
                        <referenceField2/>
                   </createStatus>
            </orderStatus>
        ';

        }elseif ($status == "P"){
            return '
            <orderStatus>
                  <siteId>W148</siteId>
                  <countryCode>CN</countryCode>
                  <statusdateTime>' . $messageDateTime . '</statusdateTime>
                  <consignmentNumber>' . $sn . '</consignmentNumber>
                  <consignmentLineItemNumber>6</consignmentLineItemNumber>
                  <salesOrderNumber>' . $channel_order_id . '</salesOrderNumber>
                  <salesOrderLineItemNumber>' . $order_line_id . '</salesOrderLineItemNumber>
                  <status>P</status>
                  <sku>' . $goods_sku_sn . '</sku>
                   <pickStatus>
                        <orderVersion>T</orderVersion>
                        <quantity>1</quantity>
                        <carrierName>SF</carrierName>
                        <referenceField1>' . $order_sn . '</referenceField1>
                        <referenceField2/>
                   </pickStatus>
            </orderStatus>
        ';
        }elseif ($status == "D"){
            return '
            <orderStatus>
                  <siteId>W148</siteId>
                  <countryCode>CN</countryCode>
                  <statusdateTime>' . $messageDateTime . '</statusdateTime>
                  <consignmentNumber>' . $sn . '</consignmentNumber>
                  <consignmentLineItemNumber>6</consignmentLineItemNumber>
                  <salesOrderNumber>' . $channel_order_id . '</salesOrderNumber>
                  <salesOrderLineItemNumber>' . $order_line_id . '</salesOrderLineItemNumber>
                  <status>D</status>
                  <sku>' . $goods_sku_sn . '</sku>
                  <deliveredStatus>
                        <orderVersion>T</orderVersion>
                        <wmsInternalParcelNumber/>
                        <quantity>1</quantity>
                        <season>201807</season>
                        <countryOfOrigin>IN</countryOfOrigin>
                        <hmOrder>194735</hmOrder>
                        <shipmentNumber/>
                        <carrierName>SF</carrierName>
                        <carrierTrackingNumber>767606119183</carrierTrackingNumber>
                        <trackingHyperlink>http://www.sf-express.com/</trackingHyperlink>
                        <referenceField1>' . $order_sn . '</referenceField1>
                        <referenceField2/>
                   </deliveredStatus>
            </orderStatus>
        ';
        }

    }
}


//return $status?'
//            <orderStatus>
//                  <siteId>W148</siteId>
//                  <countryCode>CN</countryCode>
//                  <statusdateTime>' . $messageDateTime . '</statusdateTime>
//                  <consignmentNumber>' . $sn . '</consignmentNumber>
//                  <consignmentLineItemNumber>6</consignmentLineItemNumber>
//                  <salesOrderNumber>' . $channel_order_id . '</salesOrderNumber>
//                  <salesOrderLineItemNumber>' . $order_line_id . '</salesOrderLineItemNumber>
//                  <status>F</status>
//                  <sku>' . $goods_sku_sn . '</sku>
//                  <failedDeliveryStatus>
//                    <orderVersion>T</orderVersion>
//                    <wmsInternalParcelNumber/>
//                    <quantity>1</quantity>
//                    <season>201808</season>
//                    <countryOfOrigin>CN</countryOfOrigin>
//                    <hmOrder>111313</hmOrder>
//                    <shipmentNumber/>
//                    <carrierName>SF</carrierName>
//                    <carrierTrackingNumber>767609217849</carrierTrackingNumber>
//                    <trackingHyperlink>http://www.sf-express.com/</trackingHyperlink>
//                    <referenceField1>' . $order_sn . '</referenceField1>
//                    <referenceField2/>
//                  </failedDeliveryStatus>
//            </orderStatus>
//        ':'
//           <orderStatus>
//                        <siteId>W148</siteId>
//                        <countryCode>CN</countryCode>
//                        <statusdateTime>' . $messageDateTime . '</statusdateTime>
//                        <consignmentNumber>' . $sn . '</consignmentNumber>
//                        <consignmentLineItemNumber>6</consignmentLineItemNumber>
//                        <salesOrderNumber>' . $channel_order_id . '</salesOrderNumber>
//                        <salesOrderLineItemNumber>' . $order_line_id . '</salesOrderLineItemNumber>
//                        <status>S</status>
//                        <sku>' . $goods_sku_sn . '</sku>
//                        <shippedStatus>
//                            <orderVersion>T</orderVersion>
//                            <wmsInternalParcelNumber/>
//                            <quantity>1</quantity>
//                            <season>201808</season>
//                            <countryOfOrigin>BD</countryOfOrigin>
//                            <hmOrder>141540</hmOrder>
//                            <shipmentNumber>1234567890</shipmentNumber>
//                            <carrierName>SF</carrierName>
//                            <carrierTrackingNumber>1234567890</carrierTrackingNumber>
//                            <trackingHyperlink>http://www.sf-express.com/</trackingHyperlink>
//                            <referenceField1>' . $order_sn . '</referenceField1>
//                            <referenceField2/>
//                        </shippedStatus>
//                    </orderStatus>
//        ';
